package de.gwtprime.client.login;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.PrimeService;
import de.gwtprime.client.PrimeServiceAsync;
import de.gwtprime.client.event.AuthenticationEvent;
import de.gwtprime.client.event.AuthenticationEvent.AuthenticationEventType;
import de.gwtprime.client.util.AppUtils;
import de.gwtprime.shared.requestFactory.User2Proxy;

/**
 * Represents the login-box
 * @author jan
 *
 */
public class LogoutContainer extends Composite {

	/**
	 * Create a remote service proxy to talk to the server-side Prime service.
	 */
	private final PrimeServiceAsync primeService = GWT
			.create(PrimeService.class);
	
	interface MyUiBinder extends UiBinder<Widget, LogoutContainer> {}
	private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

	private ClientFactory clientFactory;
	
	@UiField Label userNameLabel;
	@UiField Anchor logoutButton;

	public LogoutContainer(ClientFactory clientFactory) {
		// sets listBox
		initWidget(uiBinder.createAndBindUi(this));

		this.clientFactory = clientFactory;
		userNameLabel.setText("Test user");

	}

	@UiHandler("logoutButton")
	void handleClick(ClickEvent e) {
		
		AuthenticationEvent event = new AuthenticationEvent(AuthenticationEventType.LOGOUT);
		
		clientFactory.getEventBus().fireEvent(event);
		
		primeService.logout(new AsyncCallback<Void>() {
			
			@Override
			public void onSuccess(Void result) {
				AppUtils.log("Logout was successful");
			}
			
			@Override
			public void onFailure(Throwable caught) {
				AppUtils.log("Logout failed");
			}
		});
	}
	
	public void setVisible(User2Proxy user){
		userNameLabel.setText(user.getEmail());
		setVisible(true);
	}
}
